package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.MarketService;
import com.cskaoyan.utils.FileUploadUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MarketServiceImpl implements MarketService {
    @Value("${upload.picture.path}")
    String localPath;
    @Autowired
    CskaoyanmallRegionMapper regionmapper;
    @Autowired
    CskaoyanmallBrandMapper brandMapper;
    @Autowired
    CskaoyanmallStorageMapper storageMapper;
    @Autowired
    CskaoyanmallCategoryMapper categoryMapper;
    @Autowired
    CskaoyanmallOrderMapper orderMapper;
    @Autowired
    CskaoyanmallOrderGoodsMapper orderGoodsMapper;
    @Autowired
    CskaoyanmallUserMapper userMapper;
    @Autowired
    CskaoyanmallIssueMapper issueMapper;

    @Autowired
    CskaoyanmallKeywordMapper keywordMapper;

    @Override
    //获取省市区的全部数据
    public List<ProvinceVo> selectProvinces() {
        List<ProvinceVo> provinceVoList = regionmapper.selectProvincesByType();
        //获取全部的省份list,遍历，获取每一个省份对应的下级市
        for (ProvinceVo pv : provinceVoList) {
            //获取省份id
            Integer pid = pv.getId();
            //通过id得到下级市的list
            List<City> cityList = regionmapper.selectCityById(pid);
            //遍历list 获取下级市对应的区
            for (City c : cityList) {
                Integer cid = c.getId();
                List<Region> regionList = regionmapper.selectRegionById(cid);
                //获取区对应的list,添加进城市的children里面
                c.setChildren(regionList);

            }
            //将每个封装好的城市添加进相对应省的list<children>
            pv.setChildren(cityList);

        }
        return provinceVoList;
    }

    @Override
    //获取品牌商的分页数据
    public AllBrandVo allBrandService(AllBrandBo allBrandBo) {
        //获取对象所携带的信息
        Integer limit = allBrandBo.getLimit();
        Integer page = allBrandBo.getPage();
        String order = allBrandBo.getOrder();
        String sort = allBrandBo.getSort();
        //通过插件来实现分页功能
        List<CskaoyanmallBrand> brandList;
        long total;

        PageHelper.startPage(page, limit);
        CskaoyanmallBrandExample brandExample = new CskaoyanmallBrandExample();
        if (allBrandBo.getId() != null || allBrandBo.getName() != null) {
            //当传入的参数有name,id,则是查询品牌商
            CskaoyanmallBrandExample.Criteria criteria = brandExample.createCriteria().andDeletedEqualTo(false);
            if (allBrandBo.getId() != null) {
                //id不能为null，加一个判断条件
                criteria.andIdEqualTo(allBrandBo.getId());
            }
            if (allBrandBo.getName()!=null) {
                criteria.andNameLike("%" + allBrandBo.getName() + "%");
            }
            //对相对应的列查询排序
            brandExample.setOrderByClause(sort + " " + order);
            brandList = brandMapper.selectByExample(brandExample);

            //获取total总数
            total = brandList.size();
        } else {
            //对相对应的列查询排序
            brandExample.setOrderByClause(sort + " " + order);
            brandExample.createCriteria().andDeletedEqualTo(false);
            brandList = brandMapper.selectByExample(brandExample);
            PageInfo<CskaoyanmallBrand> brandPageInfo = new PageInfo<>(brandList);

            //获取total总数
            total = brandPageInfo.getTotal();
        }
        //创建vo对象，将数据封装进去
        AllBrandVo allBrandVo = new AllBrandVo();
        allBrandVo.setItems(brandList);
        allBrandVo.setTotal(total);
        return allBrandVo;
    }

    @Override
    //品牌制造商添加模块
    public StorageVo addCreateService( MultipartFile multipartFile) {
        //通过工具类来保存上传的文件，返回url
        String url = FileUploadUtil.upLoad(multipartFile, localPath);
        //创建CskaoyanmallStorage 对象，接受 multipartFile中携带的参数
        CskaoyanmallStorage storage = new CskaoyanmallStorage();

        //将multipartFile中的参数传入storage
        storage.setUrl(url);
        storage.setName(multipartFile.getOriginalFilename());
        String originalFilename = multipartFile.getOriginalFilename();
        storage.setSize((int) multipartFile.getSize());
        storage.setKey(String.valueOf(UUID.randomUUID()));
        Date date = new Date();
        storage.setAddTime(date);
        storage.setUpdateTime(date);
        storage.setType(multipartFile.getContentType());


        //将对象传到数据库，这个方法哪个对象不为空，传哪个
        storageMapper.insertSelective(storage);

        //查询刚传入的数据，并获得该对象id
        CskaoyanmallStorageExample storageExample = new CskaoyanmallStorageExample();
        CskaoyanmallStorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andUrlEqualTo(url);
        List<CskaoyanmallStorage> cskaoyanmallStorages =
                storageMapper.selectByExample(storageExample);
        //将数据在数据库赋值给VO对象
        StorageVo storageVo = new StorageVo();
        CskaoyanmallStorage cs = cskaoyanmallStorages.get(0);
        storageVo.setId(cs.getId());
        storageVo.setUpdateTime(cs.getUpdateTime().toString());
        storageVo.setAddTime(cs.getAddTime().toString());
        storageVo.setKey(cs.getKey());
        storageVo.setName(cs.getName());
        storageVo.setUrl(cs.getUrl());
        storageVo.setSize(cs.getSize());


        return storageVo;
    }

    @Override //添加品牌
    public BrandBVo addBrandService(BrandBVo brand) {
        //添加时间将数据传进数据库
        Date date = new Date();
        brand.setAddTime(date);
        brand.setUpdateTime(date);

        int i = brandMapper.brandCreate(brand);//添加结束的数据

        CskaoyanmallBrandExample brandExample = new CskaoyanmallBrandExample();
        CskaoyanmallBrandExample.Criteria criteria = brandExample.createCriteria();
        if (brand.getPicUrl() != null) {
            criteria.andPicUrlEqualTo(brand.getPicUrl());
        }
//        if (brand.getName() != null) {
//            criteria.andNameEqualTo(brand.getName());
//        }
//        if (brand.getAddTime()!=null) {
//            criteria.andAddTimeEqualTo(brand.getAddTime());
//        }
        List<CskaoyanmallBrand> cskaoyanmallBrandList = brandMapper.selectByExample(brandExample);
        CskaoyanmallBrand cskaoyanmallBrand = cskaoyanmallBrandList.get(0);

        Integer id = cskaoyanmallBrand.getId();
        brand.setId(id);
        return brand;
    }

    @Override//修改品牌信息
    public CskaoyanmallBrand updateBrandService(CskaoyanmallBrand brandBVo) {
        brandMapper.updateByPrimaryKey(brandBVo);
        Integer id = brandBVo.getId();
        CskaoyanmallBrand brand = brandMapper.selectByPrimaryKey(id);
        return brand;
    }

    @Override//删除品牌信息
    public Integer deleteBrand(CskaoyanmallBrand brandB) {
        CskaoyanmallBrand brand = new CskaoyanmallBrand();
        brand.setDeleted(true);
        CskaoyanmallBrandExample brandExample = new CskaoyanmallBrandExample();
        brandExample.createCriteria().andIdEqualTo(brandB.getId());

        int i = brandMapper.updateByExampleSelective(brand, brandExample);
        return i;
    }

    @Override
    public List<CategoryList> categoryListService() {

        List<CategoryList> categoryList = categoryMapper.selectCategoryList();
        return categoryList;
    }

    @Override
    public List<CategoryL1Vo> categoryListL1Service() {
        List<CategoryL1Vo> categoryL1VoList = categoryMapper.selectCategoryListL1();
        return categoryL1VoList;
    }

    @Override
    //添加商品类目
    public CskaoyanmallCategory categoryCreateService(CskaoyanmallCategory category) {
        category.setAddTime(new Date());
        category.setUpdateTime(new Date());
        categoryMapper.insertSelective(category);

        CskaoyanmallCategory cskaoyanmallCategory = categoryMapper.selectByPrimaryKey(category.getId());
        cskaoyanmallCategory.setDeleted(null);
        cskaoyanmallCategory.setSortOrder(null);
        return cskaoyanmallCategory;
    }

    @Override
    //编辑商品类目
    public Integer categoryUpdateService(CskaoyanmallCategory category) {
        Integer id = category.getId();
        CskaoyanmallCategoryExample example = new CskaoyanmallCategoryExample();
        CskaoyanmallCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        int i = categoryMapper.updateByExampleSelective(category, example);
        return i;
    }

    @Override
    //删除商品类目
    public Integer categoryDeleteService(CategoryList categoryList) {

        Integer count = 0;
        CskaoyanmallCategory cart = new CskaoyanmallCategory();
        cart.setDeleted(true);
        CskaoyanmallCategoryExample couponExample = new CskaoyanmallCategoryExample();

        if (categoryList.getChildren()!=null) {

            List<CategoryList> children = categoryList.getChildren();
            for (CategoryList cl : children) {
                couponExample.createCriteria().andIdEqualTo(cl.getId());
                int i = categoryMapper.updateByExampleSelective(cart, couponExample);
                count += i;
            }
        }
        int i = categoryMapper.updateByExampleSelective(cart, couponExample);
        count += i;
        return count;
    }

    @Override
    //订单list
    public OrderListVo orderListService(OrderListBo orderListBo) {
        Integer limit = orderListBo.getLimit();
        String order = orderListBo.getOrder();
        Integer page = orderListBo.getPage();
        String sort = orderListBo.getSort();
        PageHelper.startPage(page, limit);

        CskaoyanmallOrderExample orderExample = new CskaoyanmallOrderExample();
        CskaoyanmallOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (orderListBo.getUserId() != null) {
            criteria.andUserIdEqualTo(orderListBo.getUserId());
        }
        if (orderListBo.getOrderSn() != null) {
            criteria.andOrderSnEqualTo(orderListBo.getOrderSn());
        }
        if (orderListBo.getOrderStatusArray()!=null) {
            ArrayList<Short> shorts = new ArrayList<>();
            Short[] orderStatusArray = orderListBo.getOrderStatusArray();
            for (int i = 0; i < orderStatusArray.length; i++) {
                shorts.add(orderStatusArray[i]);
            }
            criteria.andOrderStatusIn(shorts);
        }

        orderExample.setOrderByClause(sort + " " + order);
        List<CskaoyanmallOrder> orderList = orderMapper.selectByExample(orderExample);
        PageInfo<CskaoyanmallOrder> orderPageInfo = new PageInfo<>(orderList);
        //获取total总数
        long total = orderPageInfo.getTotal();
        for (CskaoyanmallOrder cr : orderList) {
            cr.setPayId(null);
            cr.setPayTime(null);
            cr.setShipSn(null);
            cr.setShipTime(null);
            cr.setShipChannel(null);
            cr.setConfirmTime(null);
        }
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setItems(orderList);
        orderListVo.setTotal(total);
        return orderListVo;
    }

    @Override
    public OrderDetailVo orderDetailService(Integer id) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        CskaoyanmallOrder order = orderMapper.selectByPrimaryKey(id);
        orderDetailVo.setOrder(order);
        //获取商品list
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        CskaoyanmallOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andIdEqualTo(order.getId());
        List<CskaoyanmallOrderGoods> list = orderGoodsMapper.selectByExample(orderGoodsExample);
        orderDetailVo.setOrderGoods(list);

        //获取用户信息
        CskaoyanmallUser user = new CskaoyanmallUser();
        CskaoyanmallUser u = userMapper.selectByPrimaryKey(order.getUserId());
        user.setNickname(u.getNickname());
        user.setAvatar(u.getAvatar());
        orderDetailVo.setUser(user);
        return orderDetailVo;
    }

    @Override
    //学到支付页面再写，退款
    public Integer orderRefundService(OrderRefundBo bo) {
        return null;
    }

    @Override
    public Integer OrderShipService(OrderShipBo bo) {
        CskaoyanmallOrderExample orderExample = new CskaoyanmallOrderExample();
        CskaoyanmallOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(bo.getOrderId());

        CskaoyanmallOrder order = new CskaoyanmallOrder();
        order.setShipSn(bo.getShipSn());
        order.setShipChannel(bo.getShipChannel());
        order.setShipTime(new Date());
        order.setOrderStatus((short) 301);

        int i = orderMapper.updateByExampleSelective(order, orderExample);
        return i;
    }

    @Override
    public IssueListVo issueListService(IssueListBo bo) {
        PageHelper.startPage(bo.getPage(), bo.getLimit());
        CskaoyanmallIssueExample issueExample = new CskaoyanmallIssueExample();
        CskaoyanmallIssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (bo.getQuestion()!=null) {
            criteria.andQuestionLike("%" + bo.getQuestion() + "%");
        }
        String sort = bo.getSort();
        String order = bo.getOrder();
        issueExample.setOrderByClause(sort + " " + order);
        List<CskaoyanmallIssue> issueList = issueMapper.selectByExample(issueExample);
        //总数
        PageInfo<CskaoyanmallIssue> issuePageInfo = new PageInfo<>(issueList);
        long total = issuePageInfo.getTotal();

        IssueListVo issueListVo = new IssueListVo();
        issueListVo.setTotal(total);
        issueListVo.setItems(issueList);
        return issueListVo;
    }

    @Override
    public CskaoyanmallIssue issueCreateService(CskaoyanmallIssue bo) {
        bo.setAddTime(new Date());
        issueMapper.insertSelective(bo);
        Integer id = bo.getId();
        CskaoyanmallIssue issue = issueMapper.selectByPrimaryKey(id);
        return issue;
    }

    @Override
    public CskaoyanmallIssue issueUpdateService(CskaoyanmallIssue bo) {
        bo.setUpdateTime(new Date());
        int i = issueMapper.updateByPrimaryKeySelective(bo);
        CskaoyanmallIssue issue = issueMapper.selectByPrimaryKey(bo.getId());
        return issue;
    }

    @Override
    public Integer issueDeleteService(CskaoyanmallIssue bo) {
        CskaoyanmallIssue issue = new CskaoyanmallIssue();
        issue.setDeleted(true);
        CskaoyanmallIssueExample issueExample = new CskaoyanmallIssueExample();
        issueExample.createCriteria().andIdEqualTo(bo.getId());

        int i = issueMapper.updateByExampleSelective(issue, issueExample);
        return i;
    }

    @Override
    public KeywordListVo keywordListService(KeywordListBo bo) {
        //分页功能
        PageHelper.startPage(bo.getPage(), bo.getLimit());
//排序功能
        CskaoyanmallKeywordExample keywordExample = new CskaoyanmallKeywordExample();
        keywordExample.setOrderByClause(bo.getSort() + " " + bo.getOrder());

        CskaoyanmallKeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (bo.getUrl()!=null) {
            criteria.andUrlEqualTo(bo.getUrl());
        }
        if (bo.getKeyword()!=null){
            criteria.andKeywordLike("%"+bo.getKeyword()+"%");
        }
        //获得list
        List<CskaoyanmallKeyword> keywords = keywordMapper.selectByExample(keywordExample);

        PageInfo<CskaoyanmallKeyword> pageInfo = new PageInfo<>(keywords);
        long total = pageInfo.getTotal();

        KeywordListVo keywordListVo = new KeywordListVo();
        keywordListVo.setTotal(total);
        keywordListVo.setItems(keywords);
        return keywordListVo;
    }

    @Override
    //创建关键字
    public CskaoyanmallKeyword keywordCreateService(CskaoyanmallKeyword bo) {
        bo.setAddTime(new Date());
        int i = keywordMapper.insertSelective(bo);

        CskaoyanmallKeyword keyword = keywordMapper.selectByPrimaryKey(bo.getId());
        return keyword;
    }

    @Override
    //删除关键字
    public Integer keywordDeleteService(CskaoyanmallKeyword bo) {
        CskaoyanmallKeyword keyword = new CskaoyanmallKeyword();
        keyword.setDeleted(true);
        CskaoyanmallKeywordExample keywordExample = new CskaoyanmallKeywordExample();
        keywordExample.createCriteria().andIdEqualTo(bo.getId());
        int i = keywordMapper.updateByExampleSelective(keyword, keywordExample);
        return i;
    }

    @Override
    //修改关键字
    public CskaoyanmallKeyword keywordUpdateService(CskaoyanmallKeyword bo) {
        bo.setUpdateTime(new Date());
        int i = keywordMapper.updateByPrimaryKeySelective(bo);

        CskaoyanmallKeyword keyword = keywordMapper.selectByPrimaryKey(bo.getId());
        return keyword;

    }
}